package com.yifeng.repo.base.utils.servlet;

import com.google.common.base.Strings;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by daibing on 2023/8/22.
 */
public class RequestHelper {

    public static Map<String, String> headerMap(HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String, String> headerMap = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            String header = headerNames.nextElement();
            headerMap.put(header, request.getHeader(header));
        }
        return headerMap;
    }

    public static String getRemoteHost(HttpServletRequest req) {
        String host = req.getHeader("Host");
        if (!Strings.isNullOrEmpty(host)) {
            return host;
        }
        return "-";
    }

    public static String getRemoteAddress(HttpServletRequest req) {
        String ip = req.getHeader("X-Forwarded-For");
        // proxy mode (slb|nginx)
        if (!Strings.isNullOrEmpty(ip)) {
            int pos = ip.indexOf(",");
            if (pos != -1) {
                return ip.substring(0, pos).trim();
            } else {
                return ip.trim();
            }
        }
        // not proxy mode
        return req.getRemoteAddr();
    }

    /**
     * read request body
     *
     * @param request HttpServletRequest
     * @return body content
     * @throws IOException for read failed
     */
    public static String body(HttpServletRequest request) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    }

    public static String body(BufferedReader in) throws IOException {
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    }
}
